<?php
namespace app\shop\controller;
use app\ApiRest;
use app\integral\model\Integral;
use app\shop\model\AdminShopSpePrice;
use app\shop\model\BargainAtvPv;
use app\shop\model\BargainAtvSpe;
use app\shop\model\BargainRecord;
use app\shop\model\BargainRecordList;
use app\shop\model\IndexGoods;
use app\shop\model\IndexUserInfo;
use think\App;
use app\shop\model\BargainAtv as Model;
use think\facade\Db;


class IndexBargain extends ApiRest{

    protected $model;

    protected $record_model;

    protected $record_user_model;

    protected $spe_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model  = new Model();

        $this->record_model = new BargainRecord();

        $this->spe_model = new BargainAtvSpe();

        $this->record_user_model = new BargainRecordList();

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 15:42
     * @功能说明:砍价记录的详情
     */
    public function recordInfo(){

        $input = $this->_input;
        //详情
        $data  = $this->record_model->dataInfo(['id'=>$input['id']]);

        if(empty($data)){

            $this->errorMsg('记录未找到');
        }
        //用户信息
        $data['user_info'] = Db::name('longbing_card_user')->where(['id'=>$data['user_id']])->field('nickName,avatarUrl')->find();

        $data['user_info']['avatarUrl'] = !empty($data['user_info']['avatarUrl'])?$data['user_info']['avatarUrl']:$this->defaultImage['avatar'];
        //还需要多少人砍价
        $y_num = $data['user_num'] - $data['have_num'];

        $data['y_num'] = $y_num;
        //需要砍掉的金额
        $y_price    = ($data['init_price'] - $data['low_price'])>0?$data['init_price'] - $data['low_price']:0;
        //已经砍掉的金额
//        $have_price =  ($y_price/$data['user_num'])*$data['have_num'];

        $have_price = $this->record_user_model->havePrice(['record_id'=>$input['id']]);

        $data['have_price'] = round($have_price,2);
//        //还需要砍掉的金额
//        $have_price = ($y_price/$data['user_num'])*$data['have_num'];
//
//        $data['have_price'] = round($have_price,2);
        //还差多少元
        $data['y_price']    = round($y_price - $have_price,2);

        if($y_num==0){

            $data['y_price'] = 0;

            $data['have_price'] = $data['init_price'] - $data['low_price'];
        }

        $data['over_time'] -= time();
        //弹幕消息
        $data['dm_list'] = $this->record_model->dmList($data['atv_id']);

        $data = transImagesOne($data,['goods_cover'],$this->_uniacid);

        $atv_info = $this->model->where(['id'=>$data['atv_id']])->find();
        //活动结束时间
        $data['end_time']   = $atv_info['end_time'];

        $data['end_time']   = date('Y-m-d H:i:s',$data['end_time']);
        //授权名字
        $data['name_auth']  = $atv_info['name_auth'];
        //授权电话
        $data['mobile_auth']= $atv_info['mobile_auth'];

        $data['atv_title']  = $atv_info['title'];
        //是否能砍价
        $data['can_bargain'] = $this->record_model->isBarGain($data,$this->getUserId(),$atv_info);
        //我的砍价活动的id
        $data['my_bargain_id'] = $this->record_model->where('status','in',[1,2])->where(['user_id'=>$this->getUserId(),'atv_id'=>$data['atv_id']])->value('id');

        $spe = $this->spe_model->dataInfo(['spe_id'=>$data['spe_id'],'atv_id'=>$data['atv_id']]);
        //活动商品库存
        $data['stock'] = !empty($spe['true_stock'])?$spe['true_stock']:0;
        //增加访问量
        $pv_model = new BargainAtvPv();

        $pv_model->dataAdd($this->uniacid,$data['atv_id'],$this->getUserId());

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 16:52
     * @功能说明:开始砍价
     */
    public function recordAdd(){

        $input = $this->_input;
        //活动详情
        $atv = $this->model->dataInfo(['id'=>$input['atv_id'],'status'=>1]);

        if(empty($atv)){

            $this->errorMsg('砍价活动已结束');
        }

        $spe = $this->spe_model->dataInfo(['spe_id'=>$input['spe_id'],'atv_id'=>$atv['id']]);

        $dis = [

            'user_id' => $this->getUserId(),

            'atv_id'  => $atv['id']
        ];
        //已经发起砍价的次数
        $record_ing = $this->record_model->where($dis)->where('status','in',[1,2])->find();

        if(!empty($record_ing)){

            $this->errorMsg('你有活动正在砍价中，请完成购买后才能重新发起');
        }

        $atv_count = $this->record_model->where($dis)->where('status','in',[3,5])->count();

        if($atv_count>=$atv['start_atv_times']){

            $this->errorMsg('已达到最大砍价次数');

        }

        $goods_model = new IndexGoods();

        $spe_model   = new AdminShopSpePrice();
        //查询商品信息
        $goods_info  = $goods_model->goodsInfo(['id'=>$atv['goods_id']]);
        //查询规格信息
        $o_spe = $spe_model->dataInfo(['id'=>$input['spe_id']]);

        $insert = [

            'uniacid'    => $this->_uniacid,

            'goods_id'   => $atv['goods_id'],

            'spe_id'     => $input['spe_id'],

            'atv_id'     => $atv['id'],

            'over_time'  => $atv['over_time']*3600+time(),

            'user_num'   => $atv['user_num'],

            'low_price'  => $spe['low_price'],

            'text'       => $atv['text'],

            'is_random'  => $atv['is_random'],

            'user_id'    => $this->getUserId(),

            'staff_id'   => $input['staff_id'],

            'goods_name' => $goods_info['name'],

            'goods_cover'=> $goods_info['cover'],

            'init_price' => $o_spe['price'],

            'spe_name'   => $o_spe['spe_name_text'],

        ];

        $average_price = ($insert['init_price']/$insert['low_price'])/$atv['user_num'];

        if($average_price<0.01){

            $this->errorMsg('发起失败，人均砍价最低0.01元');
        }

        $res = $this->record_model->dataAdd($insert);

        if($res!=1){

            $this->errorMsg('发起砍价失败');
        }

        $id  = $this->record_model->getLastInsID();

        return $this->success($id);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-20 17:44
     * @功能说明:帮砍列表
     */
    public function recordUserList(){

        $input = $this->_input;

        $dis = [

            'a.record_id' => $input['id']
        ];

        $data   = $this->record_user_model->dataList($dis);
        //详情
        $reocrd = $this->record_model->dataInfo(['id'=>$input['id']]);
        //需要砍掉的金额
        $y_price = ($reocrd['init_price'] - $reocrd['low_price'])>0?$reocrd['init_price'] - $reocrd['low_price']:0;

        $every_price = round($y_price/$reocrd['user_num'],2);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){
                //每笔砍掉的金额
                $v['have_price'] = $v['price'];

                $v['create_time']= date('Y-m-d H:i:s',$v['create_time']);

            }

        }

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-21 11:05
     * @功能说明:我的砍价列表
     */
    public function myRecordList(){

        $input = $this->_input;

        $dis[] = ['user_id','=',$this->getUserId()];

        $data  = $this->record_model->userRecordList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-21 15:35
     * @功能说明:帮忙砍价
     */
    public function bargainAdd(){

        $input = $this->_input;

        $record = $this->record_model->dataInfo(['id'=>$input['id']]);

        if($record['have_num']>=$record['user_num']){

            $this->errorMsg('砍价已经成功');
        }

        if($record['status']!=1){

            $this->errorMsg('砍价失效');

        }

        $atv = $this->model->dataInfo(['id'=>$record['atv_id']]);
        //是否能砍价
        $can_bargain = $this->record_model->isBarGain($record,$this->getUserId(),$atv);

        if($can_bargain!=1){

            $this->errorMsg('砍价已超过次数');

        }

        $price = $this->atvPrice($record);

        $insert = [

            'uniacid'     => $this->_uniacid,

            'user_id'     => $this->getUserId(),

            'record_id'   => $record['id'],

            'atv_id'      => $record['atv_id'],

            'price'       => $price,

            'create_time' => time()
        ];

        $bar_list_model = new BargainRecordList();

        Db::startTrans();

        $res = $bar_list_model->dataAdd($insert);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('砍价失败');
        }

        $update = [

            'have_num'    => $record['have_num']+1,
            //做一个简单的锁
            'update_time' => $record['update_time']+1,

        ];
        //砍价成功
        if($record['user_num']<=$record['have_num']+1){

            $update['status'] = 2;

            $update['success_time'] = time();

        }

        $res = $this->record_model->dataUpdate(['id'=>$record['id'],'update_time'=>$record['update_time']],$update);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('砍价失败');
        }

        Db::commit();

        return $this->success($res);

    }


    public function randFloat($min=0, $max=1){

        $a =  $min + mt_rand()/mt_getrandmax() * ($max-$min);

        $a = $a>0?$a:0;

        return round($a,2);
    }

    /**
     * @author chenniang
     * @DataTime: 2021-09-24 14:46
     * @功能说明:获取
     */
    public function atvPrice($record){
        //还剩多少人
        $y_user_num =$record['user_num']-$record['have_num'];
        //已经砍了多少钱
        $app_price  = $this->record_user_model->havePrice(['record_id'=>$record['id']]);
        //需要砍价多少钱
        $y_price    = ($record['init_price'] - $record['low_price'])>0?$record['init_price'] - $record['low_price']:0;
        //还剩多少钱
        $a_price    = ($y_price - $app_price)>0?$y_price - $app_price:0;

        if($y_user_num>1){

            if($record['is_random']==1){
                //取值最大
                $max_price = $a_price - $y_user_num*0.01;

//                $r_price   = rand(0.01,$max_price);

                $r_price   = $this->randFloat(0.01,$max_price);

            }else{

                $r_price = round($y_price/$record['user_num'],2);

            }

            return $r_price;

        }else{

            //还剩一个人对时候
            return $a_price;
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-23 09:30
     * @功能说明:用户手动取消活动
     */
    public function userCancelAtv(){

        $input = $this->_input;

        $record = $this->record_model->dataInfo(['id'=>$input['id']]);

        if(empty($record)){

            $this->errorMsg('砍价未找到');
        }

        if($record['status']!=1&&$record['status']!=2){

            $this->errorMsg('活动已结束');
        }

        $res = $this->record_model->dataUpdate(['id'=>$input['id']],['status'=>-2]);

        return $this->success($res);
    }






}
